<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%@ page import="java.util.Date"%>
<% String formId = "form_" + new Date().getTime();
   String gridId = "grid_" + new Date().getTime();
   String path = request.getContextPath()+request.getServletPath().substring(0,request.getServletPath().lastIndexOf("/")+1);
%>
<script type="text/javascript" src="<%=request.getContextPath() %>/lib/uplodifyh5/event_common.js"></script>
<script type="text/javascript">
var depDictionary = {} ;
var wardDictionary = {} ;
$(function (){
	var depAll = "";
	var contents = [{title:'请选择', value: ''}] ;
	var contents_ward = [{title:'请选择', value: ''}] ;
	var contents_groupType = [{title:'请选择', value: ''}] ;
	var grid = $('[data-role="clinicGroupGrid"]');
    var form = $("[name='clinicGroupForm']");
    var width = 200;
    var gridColumn = [
	                  	 { title: '显示顺序', name: 'groupOrder', width: 100},
	                  	 { title: '医师编码', name: 'groupCode', width: width},
	                 	 { title: '医师名称', name: 'groupName', width: width},
	                 	 { title: '医师职务', name: 'groupTypeDesc', width: width},
	                     { title: '所属科室', name: 'parDepName', width: 180 , render: function (rowdata, name, index) {
	                    	 	return mappingCodeToName(depDictionary,rowdata.parDepCode) ;
                         	 }
	                 	 },
	                     { title: '所属病区', name: 'parWardDesc', width: 180 ,render: function (rowdata, name, index) {
	                    		return mappingCodeToName(wardDictionary,rowdata.parWardCode) ;
                      		}
	                 	 }
        		 ] ;
 	
    // 根据层配置显示病区
    if( commonLayerConfig[2] == "1" ) {
    	$("#parWardCodeID").parent().prev().css("display","inline-block") ;
    	$("#parWardCodeID").parent().css("display","inline-block") ;
    } else {
    	gridColumn.splice(5,1) ;
    }
    // 初始化医师职务列表
    initeGroupTypeList() ;
	PageLoader = {
	    initSearchPanel:function(){
	    	/*加载所有科室列表*/
	    	$.ajax({
				url : contextPath + "/Department/findAllDep.dhc",
				type : "get",
				dataType : "json",
				async : false,
				success : function(result) {
						if(result.success ) {
			                depAll = result.data;
			                $.each(depAll,function(i,n){
					    		contents.push({title:n.depName, value:n.depCode});
					    		depDictionary[n.depCode] = n.depName;
			           	 });
			             form.find('#parDepCodeID').select({
					          title: '请选择',
					          contents: contents
					     }).on('change',function() {
					          form.find('#parDepCodeID_').val($(this).getValue());
					          // 将病区置为空
					          contents_ward = [{title:'请选择', value: ''}] ;
					          initeWardList(new Array($(this).getValue()),"parWardCodeID",null,form) ;
					     });
		              }
				  }
			})
	    	// 初始化病区列表
		    initeWardList("","parWardCodeID",null,form) ; 
	    },
	    initGridPanel: function(){
	         var self = this;
	         return grid.grid({
	                identity:"id",
	                buttons: [
	                        {content: '<button class="btn btn-primary" type="button"><span class="glyphicon glyphicon-plus"><span>添加</button>', action: 'add'},
	                        {content: '<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-edit"><span>修改</button>', action: 'modify'},
	                        {content: '<button class="btn btn-danger" type="button"><span class="glyphicon glyphicon-remove"><span>删除</button>', action: 'delete'},
	                        {content: '<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-cloud-upload"><span>医师数据导入</button>', action: 'import'}
	                    ],
	                url:"${pageContext.request.contextPath}/ClinicGroup/pageJson.dhc",
	                columns: gridColumn 
	         }).on({
	                   'add': function(){
	                       self.add($(this));
	                   },
	                   'modify': function(event, data){
	                	   var item = data.item;
	                        var indexs = data.data;
	                        var $this = $(this);
	                        if(indexs.length == 0){
	                            drgUI.error('请选择一条记录进行修改!');
	                            return;
	                        }
	                        if(indexs.length > 1){
	                            drgUI.warning('只能选择一条记录进行修改!');
	                            return;
	                        }
	                       self.modify(data.item[0],indexs[0], $this);
	                    },
	                   'delete': function(event, data){
	                        var indexs = data.data;
	                        var $this = $(this);
	                        if(indexs.length == 0){
	                            drgUI.warning('请选择要删除的记录!');
	                            return;
	                        }
	                        var remove = function(){
	                            self.remove(indexs, $this);
	                        };
	                        drgUI.confirm({
	                            content: '确定要删除所选记录吗?',
	                            callSure: remove
	                        });
	                   },
	                   'import' : function(event, data) {
							 $('#uploadifive-doctorInfoImport input[type="file"]:last').click() ; 
						},
	         });
	    },
	    add: function(grid){
	        var self = this;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog">'
	        	+'<div class="modal-content"><div class="modal-header"><button type="button" class="close" '
	        	+'data-dismiss="modal" aria-hidden="true">&times;</button>'
	        	+'<h4 class="modal-title">新增</h4></div><div class="modal-body">'
	        	+'<p>One fine body&hellip;</p></div><div class="modal-footer">'
	        	+'<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>'
	        	+'<button type="button" class="btn btn-success" id="save">保存</button></div></div>'
	        	+'</div></div>') ;
	        $.get('<%=path%>ClinicGroup-add.jsp').done(function(html){
	            dialog.modal({
	                keyboard:false
	            }).on({
	                'hidden.bs.modal': function(){
	                    $(this).remove();
	                }
	            }).find('.modal-body').html(html);
	            // 根据层配置显示病区
	            if( commonLayerConfig[2] == "1" ) {
	            	dialog.find("#addParWardCodeID").parents(".form-group").css("display","block") ;
	            }
	            self.initPage(dialog.find('form'));
	            initialDepSelect(dialog,"addParDepCodeID") ;
	            // initeWardList(dialog.find("#"+selectId).val(),"addParWardCodeID",dialog)  ;
	            initeWardList(null,"addParWardCodeID",dialog) ;
	        });
	        dialog.find('#save').on('click',{grid: grid}, function(e){
				var groupOrder = $("#groupOrderID").val();
				var depCode = $("#addParDepCodeID").val();
				var wardCode = $("#addParWardCodeID").val();
				var groupCode = $("#groupCodeID").val();
				// 验证是否通过
				var flag = true ;
				dialog.find("input[datatype='Require']").each(function(index,element){
					if($(element).val()=="") {
						$(element).focus();
						drgUI.error('带*的为必选项!');
						flag = false ;
						return flag ;
					}
				})
				if(!flag) { //验证未通过
					return ;
				}
		        $.post('${pageContext.request.contextPath}/ClinicGroup/isGroupCodeOrOrderExist.dhc',{"groupCode":groupCode,"groupOrder":groupOrder}).done(function(result){
		        	  if(result.data.flag_code) {
		        		  drgUI.error('医师编码已存在，请重新输入!');
		        	  } else if(result.data.flag_order) {
		        		  drgUI.error('显示顺序已存在，请重新输入!');
		        	  } else { 
		        		  var param = dialog.find('form').serializeJson() ;
		        		   $.post('${pageContext.request.contextPath}/ClinicGroup/add.dhc', {"param":JSON.stringify(param)}).done(function(result){
		                   if(result.success ){
		                        dialog.modal('hide');
		                        e.data.grid.data('koala.grid').refresh();
		                        drgUI.success('保存成功!');
		                    }else{
		                     	drgUI.error(result.actionError);
		                     }
		                 });
		        	  }
		          });
		    });
		},
	    modify: function(item,id, grid) {
	        var self = this;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">修改</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-success" id="save">保存</button></div></div></div></div>');
	        $.get('<%=path%>/ClinicGroup-update.jsp').done(function(html){
	               dialog.find('.modal-body').html(html);
	               // 根据层配置显示病区
		           if( commonLayerConfig[2] == "1" ) {
		            	dialog.find("#updateParWardCodeID").parents(".form-group").css("display","block") ;
		           }
	               self.initPage(dialog.find('form'));
	               // 初始化下拉框并设置默认值
	               initialDepSelect(dialog,"updateParDepCodeID",item.parDepCode.split(",")) ;
	               initeWardList(item.parDepCode.split(","),"updateParWardCodeID",dialog,null,item.parWardCode.split(","))
	               dialog.find('#groupOrderID').val($.trim(item.groupOrder));
	               dialog.find('#groupCodeID').val($.trim(item.groupCode));
	               dialog.find('#groupCodeID_hidden').val($.trim(item.groupCode));
	               dialog.find('#groupNameID').val($.trim(item.groupName));
	               dialog.find("#updateGroupTypeID").setValue(item.groupType);
	               dialog.find("#updateParDepCodeID_").val(item.parDepCode.split(","));
	               dialog.find("#updateParWardCodeID_").val(item.parWardCode.split(","));
	               dialog.find('#idID').val(id);
	               dialog.modal({
	                    keyboard:false
	               }).on({
	                    'hidden.bs.modal': function(){
	                        $(this).remove();
	                    }
	               });
	               dialog.find('#save').on('click',{grid: grid}, function(e){
	                	if(!Validator.Validate(dialog.find('form')[0],3))return;
	                	var param = dialog.find('form').serializeJson() ;
	                	$.post('${pageContext.request.contextPath}/ClinicGroup/isGroupCodeExist.dhc',{"groupCode":dialog.find('#groupCodeID_hidden').val(),"groupOrder":dialog.find('#groupOrderID').val()}).done(function(result){
	                		if(result) {
	                			drgUI.error('显示顺序已存在，请重新输入!');
	                		} else {
	                			$.post('${pageContext.request.contextPath}/ClinicGroup/add.dhc', {"param":JSON.stringify(param)} ).done(function(result){
			                        if(result.success){
			                            dialog.modal('hide');
			                            e.data.grid.data('koala.grid').refresh();
			                            drgUI.success('保存成功!');
			                        } else {
			                            drgUI.error(result.actionError);
			                        }
			                    });
	                		}
	                	})
	                });
	        });
	    },
	    initPage: function(form){
             form.find('.form_datetime').datetimepicker({
                  language: 'zh-CN',
                  format: "yyyy-mm-dd",
                  autoclose: true,
                  todayBtn: true,
                  minView: 2,
                  pickerPosition: 'bottom-left'
              }).datetimepicker('setDate', new Date());//加载日期选择器
              form.find('.select').each(function(){
                   var select = $(this);
                   var idAttr = select.attr('id');
                   var title = "请选择" ;
                   var content = [] ;
                   if ( idAttr.indexOf("GroupTypeID") > 0 ) {
                   	content = contents_groupType ;
                   } 
                   select.select({
                       title: title,
                       contents: content
                   }).on('change', function(){
                       form.find('#'+ idAttr + '_').val($(this).getValue());
                   }); 
              });
	    },
	    remove: function(ids, grid){
	    	var data = [{ name: 'ids', value: ids.join(',') }];
	    	$.post('${pageContext.request.contextPath}/ClinicGroup/delete.dhc', data).done(function(result){
                  if(result.success){
                      grid.data('koala.grid').refresh();
                      drgUI.success('删除成功!');
                  }else{
                      drgUI.error(result.result);
                  }
	    	});
	    }
	}
	
    PageLoader.initSearchPanel();
	PageLoader.initGridPanel();
	
	// 下载按钮
	var downloadBtn = '<div class="btn-clickable">' ;
	downloadBtn+='<a href="download/doctor.xlsx" class="link text-sm" style = "text-decoration:none;color:#fff">' ;
	downloadBtn+='<i class="fa fa-download"></i>&nbsp;下载模版' ;
	downloadBtn+='</a>' ;
	downloadBtn+='</div>' ;
	$(<%=gridId%>).find("thead > tr > th").append(downloadBtn) ;
	
	form.find('#search').on('click', function(){
			if(!Validator.Validate(document.getElementById("<%=formId%>"),3))return;
            var params = {};
            form.find('input').each(function(){
                var $this = $(this);
                var name = $this.attr('name');
                if(name){
                    params[name] = $this.val();
                }
            });
            $('[data-role="clinicGroupGrid"]').getGrid().search(params);
     });
	
	 /**
     * 获取所有科室信息
     */
    function initialDepSelect(dialog,selectId,selectedVal) {	
    	//获取所有科室列表
    	$.ajax({
    		url : contextPath + "/Department/findAllDep.dhc",
    		type : "post",
    		dataType : "json",
    		async : false,
    		success : function(result) {
    			var data = result.data;
    			var optStr = "";
    			for(var i = 0;i<data.length;i++)
    			{
					optStr = optStr + '<option value="'+data[i].depCode+'">'+data[i].depName+'</option>';
    			}
    			//多选下拉框初始化
    			dialog.find("#"+selectId).append(optStr);
    			dialog.find("#"+selectId).multiselect({
    				includeSelectAllOption: true  ,
    				selectAllText: '全选选择' ,
    				allSelectedText: '全部选择' ,
    				maxHeight: 150, 
    				onChange: function(option, checked, select) {
    		        	dialog.find("form").find('#'+ selectId + '_').val(dialog.find("#"+selectId).val());
    		        } ,
    				onDropdownHidden: function(event) {
    					if(selectId == "addParDepCodeID") {
    						initeWardList(dialog.find("#"+selectId).val(),"addParWardCodeID",dialog)  ;
    					} else {
    						initeWardList(dialog.find("#"+selectId).val(),"updateParWardCodeID",dialog)  ;
    					}
    		        }
    			});
    			// 设置默认选项
    			if (selectedVal && selectedVal.length > 0) {
    				dialog.find("#"+selectId).multiselect('select', selectedVal);
    			}
    		}
    	});
    }
	
	function initeWardList(depCode,selectId,dialog,form,selectedVal) {
		// 没有配置病区不再请求
		if(commonLayerConfig[2] == "0") {
			return ;
		}
		$.ajax({  
	          type : "post",  
	          url : '${pageContext.request.contextPath}/Ward/findWardByDepCode.dhc',
	          data : {"depCode":depCode},  
	          async : false,  
	          success : function(result){  
	        	   if(result.success ) {
		               wardAll = result.data ;
		               var optStr = "" ;
		               $.each(wardAll,function(i,n){
					   		optStr = optStr + '<option value="'+n.wardCode+'">'+n.wardDesc+'</option>';
					   		contents_ward.push({title:n.wardDesc, value:n.wardCode});
					   		wardDictionary[n.wardCode] = n.wardDesc;
		          	   });
		               if(optStr=="") {
					   		optStr = optStr + '<option >无病区数据</option>';
		                }
		               if(form) {
			           		var title = "请选择" ;
			                // 如果没有病区数据
			                if(contents_ward.length == 1){
			               		title = "无病区数据" ;
			                }
				            form.find('#'+selectId+'').select({
						        title: title ,
						        contents: contents_ward
						    }).on('change',function() {
						        form.find('#'+selectId+'_').val($(this).getValue());
						    });
		               } else {
			                dialog.find("#"+selectId+"").empty();
			                dialog.find("#"+selectId+"").multiselect('destroy') ;
						    dialog.find("#"+selectId+"").append(optStr);
						    //多选下拉框初始化
			    			dialog.find("#"+selectId+"").multiselect({
			    				includeSelectAllOption: true  ,
			    				selectAllText: '全选选择' ,
			    				allSelectedText: '全部选择' ,
			    				maxHeight: 150 ,
			    				// 为相应的输入框赋值，便于表单转json
			    				onChange: function(option, checked, select) {
			    		        	dialog.find("form").find('#'+ selectId + '_').val(dialog.find("#"+selectId).val());
			    		        } 
			    			});
						    // 设置默认选项
						    if(selectedVal && selectedVal.length>0) {
			    				dialog.find("#"+selectId).multiselect('select', selectedVal);
						    }
		               }
		          } 
	          }  
	     });  
	}
	// 初始化医师职务下拉列表
	function initeGroupTypeList() {
		// 没有配置病区不再请求
		$.ajax({  
	          type : "post",
	          url : '${pageContext.request.contextPath}/dictionaryData/getDictionaryDataByCode.dhc',
	          data : {"dicCode":"DOCTOR_TYPE"},  
	          async : false,  
	          success : function(result){
	        	  var groupTypeAll = result.data;
	        	   if( groupTypeAll ) {
		               var groupTypeAll = result.data;
		               $.each(groupTypeAll,function(i,n){
		               	contents_groupType.push({title:n.DICDESC, value:n.DICVALUE});
		          	   });
		          } 
	          }  
	     }); 
	}
	
	$.fn.serializeJson=function() {
        var serializeObj={};  
        var array=this.serializeArray();  
        var str=this.serialize();  
        $(array).each(function(){  
            if(serializeObj[this.name]){  
                if($.isArray(serializeObj[this.name])){  
                    serializeObj[this.name].push(this.value);  
                }else{  
                    serializeObj[this.name]=[serializeObj[this.name],this.value];  
                }  
            }else{  
                serializeObj[this.name]=this.value;   
            }  
        });  
        return serializeObj;  
    }
	
	// 插件初始化
    $('#'+tabId+' #doctorInfoImport').uploadifive({
		'uploadScript' : contextPath + '/fileUpload/filesUpload.dhc',
        'height': 37,
        'width' :140,
        'auto'  : true,//是否自动开始
        'uploadLimit' : 10, //一次同步上传的文件数目     
        'fileSizeLimit' : '500MB', //单个文件大小，0为无限制，可接受KB,MB,GB等单位的字符串值     
        'queueSizeLimit' : 100, //队列中同时存在的文件个数限制
        'fileObjName':'file',
        'removeCompleted': false,  //是否完成后移除序列，默认为true
        'removeTimeout' : '5',  //上传完成后队列多长时间后消失。默认 3秒    需要：removeCompleted : true,时使用
        'buttonText' : '<i class="fa fa-folder-open fa-lg"></i>&nbsp;&nbsp;费用子项上传',
        'fileType' : '*.xls; *.xlsx; *.xml; *.dbf',//允许上传的文件格式
        'multi'    : true,//是否支持多文件上传
        'method'   :'post',//提交方式
        'debug':false,
        //当点击文件队列中文件的关闭按钮或点击取消上传时触发
        'onCancel': function(){ },
      	//返回一个错误，选择文件的时候触发  
        'onSelectError':  function(){
        	  drgUI.error('文件上传失败！');
        },
      	//检测FLASH失败调用  
        'onFallback':function(){  
            drgUI.error('浏览器检测不到兼容版本的HTML5！');
        }, 
        'onUpload': function(filesToUpload) {
        	$("#uploadifive-doctorInfoImport-queue").css("display","none") ;
        },
        'onUploadError' : uploadify_onUploadError,
        'onQueueComplete':function(queueData){
        	//closeBgDiv();
        	//showBgDiv();//显示遮罩层
        	//drgUI.bindAjaxStart(0) ;
        	//getProgress();
        	$.post(contextPath+'/fileUpload/doctorInfoImport.dhc').done(function(result){
        		var message = "" ;
        		if(result.success) {
        			message = result.data ;
        		} else {
        			message = result.errorMessage ;
        		}
        		drgUI.alert(message,function(){
        			$('[data-role="clinicGroupGrid"]').grid('refresh');
        		});
        	});
        }
    });
 	$("#uploadifive-doctorInfoImport").css("display","none") ;
});

// 查看操作
var openClinicGroupDetailsPage = function(rowdata) {
    var dialog = $('<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">查看</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-info" data-dismiss="modal">返回</button></div></div></div></div>');
    $.get('<%=path%>/ClinicGroup-view.jsp').done(function(html){
           dialog.find('.modal-body').html(html);
           // 根据层配置显示病区
           if( commonLayerConfig[2] == "1" ) {
            	dialog.find("#parWardDescID").parents(".form-group").css("display","block") ;
           }
           rowdata = JSON.parse(JSON.stringify(rowdata).replace(/\'/g,"\"")) ;
           dialog.find("#groupCodeID").html(rowdata.groupCode);
           dialog.find("#groupNameID").html(rowdata.groupName);
           dialog.find("#groupTypeDescID").html(rowdata.groupTypeDesc);
           dialog.find("#groupOrderID").html(rowdata.groupOrder);
           dialog.find("#parDepNameID").html(mappingCodeToName(depDictionary,rowdata.parDepCode));
           dialog.find("#parWardDescID").html(mappingCodeToName(wardDictionary,rowdata.parWardCode));
           dialog.modal({
                keyboard:false
           }).on({
                'hidden.bs.modal': function(){
                    $(this).remove();
                }
           });
    });
}
//将编码映射为描述
function mappingCodeToName(dictionary,code) {
	var code = code.split(",") ;
	var desc = "" ;
	for(var o in code) {
		if(dictionary[code[o]]) {
			desc += dictionary[code[o]] + "," ;
		} else {
			desc += code[o] + "," ;
		}
	}
	return desc.substring(0,desc.length-1) ;
}
</script>
</head>
<body>
<div style="width:98%;margin-right:auto; margin-left:auto; padding-top: 15px;">
<!-- search form -->
<%-- <form name="clinicGroupForm" id=<%=formId%> target="_self" class="form-horizontal">
			
<table border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
		<div class="form-group">
			<label class="control-label" style="width:100px;float:left;">医师名称:&nbsp;</label>
			<div style="margin-left:15px;float:left;">
			<input name="groupName" class="form-control" type="text" style="width:180px;" id="groupNameID"  />
		</div>
        
          <label class="control-label" style="width:100px;float:left;">所属科室:&nbsp;</label>
          <div style="margin-left:15px;float:left;">
		      <div class="btn-group select" id="parDepCodeID"></div>
		      <input type="hidden" id="parDepCodeID_" name="parDepCode" />
	      </div>
	      
          <label class="control-label" style="width:100px;float:left;display:none">所属病区:&nbsp;</label>
          <div style="margin-left:15px;float:left;display:none">
		      <div class="btn-group select" id="parWardCodeID"></div>
		      <input type="hidden" id="parWardCodeID_" name="parWardCode" />
	      </div>
        </div>
   </td>
       <td style="vertical-align: bottom;"><button id="search" type="button" style="position:relative; margin-left:35px; top: -15px" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>&nbsp;查询</button></td>
  </tr>
</table>	
</form> --%>
<form name="clinicGroupForm" id=<%=formId%> target="_self" class="form-horizontal">
	<div class="container-fluid">
		<div class="row">
		<div class="form-group col-md-4">
			<label>医师名称:&nbsp;</label>
			<input name="groupName" class="form-control" type="text" style="width:180px;" id="groupNameID"  />
		</div>
		<div class="form-group col-md-3">
			<label>所属科室:&nbsp;</label>
			<div class="btn-group select" id="parDepCodeID"></div>
		    <input type="hidden" id="parDepCodeID_" name="parDepCode" />
		</div>
		
		<div class="form-group col-md-1">
			<button id="search" type="button"  class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>&nbsp;查询</button>
		</div>
		</div>
	</div>
</form>
<!-- grid -->
<div id=<%=gridId%> data-role="clinicGroupGrid" ></div>
<!-- 医师数据导入 --><!--  -->
<div><input id="doctorInfoImport" type="file" name="doctorInfoImport" style="display: none;"/></div>
</div>
</body>
</html>
